import 'dart:io';
import 'dart:math';
import 'dart:math' as math;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:url_launcher/url_launcher.dart';

AppBar buildAppBar(String title, List<Widget> actions, BuildContext context) {
  return AppBar(
    //导航栏
    title: Text(title),
//      centerTitle: true,
//      leading: IconButton(
//        icon: Image.asset('assets/back.png',width: 20,height: 20,), //自定义图标
//        onPressed: () {
//          Navigator.pop(context);
//        },
//      ),
//      actions: actions,
//      elevation: 0.5,
//      flexibleSpace: Store.connect<MyProvider>(
//          builder: (context, MyProvider provider, child) {
//            return Container(
//              decoration: BoxDecoration(
//                  color: Colors.white),
//            );
//          }),
//      brightness: Brightness.light,
  );
}

bool isNullOrEmpty(String str) {
  return str == null || str.length == 0;
}

void showToast(String msg) {
  Fluttertoast.showToast(
      msg: msg,
      gravity: ToastGravity.CENTER,
      backgroundColor: Colors.black,
      textColor: Colors.white);
}

/// 高德地图
Future<bool> gotoAMap(longitude, latitude) async {
  var url =
      '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';

  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('未检测到高德地图~');
    return false;
  }

  await launch(url);

  return true;
}

/// 腾讯地图
Future<bool> gotoTencentMap(longitude, latitude) async {
  var url =
      'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';
  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('未检测到腾讯地图~');
    return false;
  }

  await launch(url);

  return canLaunchUrl;
}

/// 百度地图
Future<bool> gotoBaiduMap(longitude, latitude) async {
  var url =
      'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';

  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('未检测到百度地图~');
    return false;
  }

  await launch(url);

  return canLaunchUrl;
}

/// 苹果地图
Future<bool> gotoAppleMap(longitude, latitude) async {
  var url = 'http://maps.apple.com/?&daddr=$latitude,$longitude';

  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('打开失败~');
    return false;
  }

  await launch(url);
}

/// 苹果App Store
Future<bool> gotoAppStore() async {
  var url = 'https://apps.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id1488412445';

  bool canLaunchUrl = await canLaunch(url);

  if (!canLaunchUrl) {
    showToast('打开失败~');
    return false;
  }

  await launch(url);
}

//size.substring(0,size.indexOf(".")+3) 小数点位数
String getPrintSize(limit) {
  String size = "";
  //内存转换
  if (limit < 1 * 1024) {
    //小于0.1KB，则转化成B
    size = limit.toString();
    size = size.substring(0, size.indexOf(".") + 3) + "  B";
  } else if (limit < 1 * 1024 * 1024) {
    //小于0.1MB，则转化成KB
    size = (limit / 1024).toString();
    size = size.substring(0, size.indexOf(".") + 3) + "  KB";
  } else if (limit < 1 * 1024 * 1024 * 1024) {
    //小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toString();
    print(size.indexOf("."));
    size = size.substring(0, size.indexOf(".") + 3) + "  MB";
  } else {
    //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toString();
    size = size.substring(0, size.indexOf(".") + 3) + "  GB";
  }
  return size;
}

var lastPopTime;
bool isFastClick() {
  // 防重复提交
  if (lastPopTime == null ||
      DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
    lastPopTime = DateTime.now();
    return false;
  } else {
    lastPopTime = DateTime.now();
//    showToast("请勿重复点击！");
    return true;
  }
}

void hideKeyboard(BuildContext context) {
  FocusScopeNode currentFocus = FocusScope.of(context);
  if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
    FocusManager.instance.primaryFocus.unfocus();
  }
}

var signs = [
  '保内安装',
  '待预约',
  '配件待审核',
  '配件审核通过',
  '催单',
  '费用待审核',
  '费用审核不通过',
  '超时未预约',
  '今日需上门',
  '超时未上门',
  '新留言'
];
var colors = [
  Color(0xff2196F3),
  Color(0xffFD8387),
  Color(0xff5AFF15),
  Color(0xffC100FD),
  Color(0xffB4D1FB),
  Color(0xffFF67C5),
  Color(0xff88FFD6),
];

const double _degrees2Radians = math.pi / 180.0;

/// Converts degrees to radians
double radians(double degrees) => degrees * _degrees2Radians;

const double _radians2Degrees = 180.0 / math.pi;

/// Converts radians to degrees
double degrees(double radians) => radians * _radians2Degrees;

/// Returns a default size based on the screen size
/// that is a 70% scaled square based on the screen.
Size getDefaultSize(Size screenSize) {
  Size resultSize;
  if (screenSize.width < screenSize.height) {
    resultSize = Size(screenSize.width, screenSize.width);
  } else if (screenSize.height < screenSize.width) {
    resultSize = Size(screenSize.height, screenSize.height);
  } else {
    resultSize = Size(screenSize.width, screenSize.height);
  }
  return resultSize * 0.7;
}

/// Forward the view base on its degree
double translateRotatedPosition(double size, double degree) {
  return (size / 4) * math.sin(radians(degree.abs()));
}

/// Decreases [borderRadius] to <= width / 2
BorderRadius normalizeBorderRadius(BorderRadius borderRadius, double width) {
  if (borderRadius == null) {
    return null;
  }

  Radius topLeft;
  if (borderRadius.topLeft.x > width / 2 ||
      borderRadius.topLeft.y > width / 2) {
    topLeft = Radius.circular(width / 2);
  } else {
    topLeft = borderRadius.topLeft;
  }

  Radius topRight;
  if (borderRadius.topRight.x > width / 2 ||
      borderRadius.topRight.y > width / 2) {
    topRight = Radius.circular(width / 2);
  } else {
    topRight = borderRadius.topRight;
  }

  Radius bottomLeft;
  if (borderRadius.bottomLeft.x > width / 2 ||
      borderRadius.bottomLeft.y > width / 2) {
    bottomLeft = Radius.circular(width / 2);
  } else {
    bottomLeft = borderRadius.bottomLeft;
  }

  Radius bottomRight;
  if (borderRadius.bottomRight.x > width / 2 ||
      borderRadius.bottomRight.y > width / 2) {
    bottomRight = Radius.circular(width / 2);
  } else {
    bottomRight = borderRadius.bottomRight;
  }

  return BorderRadius.only(
    topLeft: topLeft,
    topRight: topRight,
    bottomLeft: bottomLeft,
    bottomRight: bottomRight,
  );
}

/// Lerps between a [LinearGradient] colors, based on [t]
Color lerpGradient(List<Color> colors, List<double> stops, double t) {
  final length = colors.length;
  if (stops.length != length) {
    /// provided gradientColorStops is invalid and we calculate it here
    stops = List.generate(length, (i) => (i + 1) / length);
  }

  for (var s = 0; s < stops.length - 1; s++) {
    final leftStop = stops[s], rightStop = stops[s + 1];
    final leftColor = colors[s], rightColor = colors[s + 1];
    if (t <= leftStop) {
      return leftColor;
    } else if (t < rightStop) {
      final sectionT = (t - leftStop) / (rightStop - leftStop);
      return Color.lerp(leftColor, rightColor, sectionT);
    }
  }
  return colors.last;
}

/// Returns an efficient interval for showing axis titles, or grid lines or ...
///
/// If there isn't any provided interval, we use this function to calculate an interval to apply,
/// using [axisViewSize] / [pixelPerInterval], we calculate the allowedCount lines in the axis,
/// then using  [diffInYAxis] / allowedCount, we can find out how much interval we need,
/// then we round that number by finding nearest number in this pattern:
/// 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 5000, 10000,...
double getEfficientInterval(double axisViewSize, double diffInYAxis,
    {double pixelPerInterval = 10}) {
  final allowedCount = axisViewSize ~/ pixelPerInterval;
  final accurateInterval = diffInYAxis / allowedCount;
  return roundInterval(accurateInterval).toDouble();
}

int roundInterval(double input) {
  var count = 0;

  if (input >= 10) {
    count++;
  }

  while (input ~/ 100 != 0) {
    input /= 10;
    count++;
  }

  final scaled = input >= 10 ? input.round() / 10 : input;

  if (scaled >= 2.6) {
    return 5 * pow(10, count).toInt();
  } else if (scaled >= 1.6) {
    return 2 * pow(10, count).toInt();
  } else {
    return pow(10, count).toInt();
  }
}

/// billion number
/// in short scale (https://en.wikipedia.org/wiki/Billion)
const double billion = 1000000000;

/// million number
const double million = 1000000;

/// kilo (thousands) number
const double kilo = 1000;

/// Formats and add symbols (K, M, B) at the end of number.
///
/// if number is larger than [billion], it returns a short number like 13.3B,
/// if number is larger than [million], it returns a short number line 43M,
/// if number is larger than [kilo], it returns a short number like 4K,
/// otherwise it returns number itself.
/// also it removes .0, at the end of number for simplicity.
String formatNumber(double number) {
  final isNegative = number < 0;

  if (isNegative) {
    number = number.abs();
  }

  String resultNumber;
  String symbol;
  if (number >= billion) {
    resultNumber = (number / billion).toStringAsFixed(1);
    symbol = 'B';
  } else if (number >= million) {
    resultNumber = (number / million).toStringAsFixed(1);
    symbol = 'M';
  } else if (number >= kilo) {
    resultNumber = (number / kilo).toStringAsFixed(1);
    symbol = 'K';
  } else {
    resultNumber = number.toStringAsFixed(1);
    symbol = '';
  }

  if (resultNumber.endsWith('.0')) {
    resultNumber = resultNumber.substring(0, resultNumber.length - 2);
  }

  if (isNegative) {
    resultNumber = '-$resultNumber';
  }

  return resultNumber + symbol;
}

Future push(BuildContext context, Widget widget) async {
  return Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
    return widget;
  }));
}
